package com.uriuniv.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.uriuniv.command.JoinCommand;
import com.uriuniv.domain.Group;
import com.uriuniv.domain.Student;
import com.uriuniv.domain.University;
import com.uriuniv.service.GroupS;
import com.uriuniv.service.StudentS;
import com.uriuniv.service.UniversityS;
import com.uriuniv.util.DateUtil;
import com.uriuniv.util.SendMail;
import com.uriuniv.util.UUIDUtil;

public class JoinC extends SimpleFormController {

	private UniversityS universityS;
	private GroupS groupS;
	private StudentS studentS;
	
	public void setUniversityS(UniversityS universityS) {
		this.universityS = universityS;
	}
	public void setGroupS(GroupS groupS) {
		this.groupS = groupS;
	}
	public void setStudentS(StudentS studentS) {
		this.studentS = studentS;
	}
	
	@Override
	protected Object formBackingObject(HttpServletRequest request)
			throws Exception {
		// TODO Auto-generated method stub
		return super.formBackingObject(request);
	}
	
	@Override
	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		
		JoinCommand joinCommand = (JoinCommand)command;
		
		String type = "일반학생";
		University university = universityS.getUniversity(joinCommand.getUniversity());
		Group group = groupS.getGroupByName(type);
		String certificationKey = UUIDUtil.getUuid();
		
		Student student = new Student();
		student.setStudentId(UUIDUtil.getUuid());
		student.setEmail(joinCommand.getEmail());
		student.setName(joinCommand.getName());
		student.setPassword(joinCommand.getPassword());
		student.setPoint(0);
		student.setTempPassword("");
		student.setJoinDate(DateUtil.getToday());
		student.setModDate(null);
		student.setUnivId(university.getUnivId());
		student.setGroupId(group.getGroupId());
		student.setCertification(certificationKey);
		
		int result = studentS.insertStudent(student);
		System.out.println(result);
		
		SendMail sendMail = new SendMail();
		String[] emailList = { joinCommand.getEmail() };// 메일 보낼사람 리스트 
		String emailFromAddress = "hanys1042@gmail.com";// 메일 보내는 사람
		String emailMsgTxt = "<a href='http://localhost:8080/uriuniv/certification.do?key=" + certificationKey + "'>회원인증</a>"; // 내용
		String emailSubjectTxt = "우리학교 회원가입 완료메일입니다.";// 제목
		sendMail.mailSend(emailList, emailFromAddress, emailMsgTxt, emailSubjectTxt);
		
		return super.onSubmit(request, response, command, errors);
	}
	
}
